# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.core.urlresolvers import reverse
from django.db.models.signals import post_save

from wlapps.utils.base62 import wlencode
from wlmodels.codes.dicts import ca23_dict, ca44_dict, ca46_dict, ca70_dict, ca71_dict, cd10_dict, ex15_dict
from wlmodels.codes.models import ELNic, ELSeic, ELCA73, ELCA75, ELCA76
from .models_plus.charge import *
from .models_plus.geti import *
from .models_plus.law import *
from .models_plus.registe import *
from .models_plus.relation import *
from .models_plus.stock import *
from .signals import save_signal_func


# 企业信息主表
class ELPost(ELBaseModel):
    entid = models.IntegerField('企业UID', unique=True)
    ENTNAME = models.CharField('企业名称', null=True, max_length=150, db_index=True)
    REGNO = models.CharField('工商注册号', null=True, blank=True, max_length=30, db_index=True)
    NACAOID = models.CharField('组织机构代码', null=True, blank=True, max_length=11, db_index=True)
    UNISCID = models.CharField('统一社会信用代码', null=True, blank=True, max_length=18, db_index=True)
    updated = models.DateTimeField('更新时间', null=True, blank=True)

    class Meta:
        verbose_name = '企业主表'
        verbose_name_plural = '企业主表'
        db_table = 'company'

    def __unicode__(self):
        if self.ENTNAME:
            return u'%s' % self.ENTNAME
        else:
            return u'%s' % self.entid

    def save(self, *args, **kwargs):
        # 自动分配新的entid
        if not self.entid:
            the_max = ELPost.objects.all().aggregate(Max('entid'))
            if the_max['entid__max']:
                self.entid = int(the_max['entid__max']) + 1
            else:
                self.entid = 1
        super(ELPost, self).save(*args, **kwargs)

    def get_report_url(self):
        url_name = "company_report"
        kwargs = {"entid": wlencode(self.entid, addcrc=True)}
        return reverse(url_name, kwargs=kwargs)

    def admin_link(self):
        return "<a href='%s' target='_blank'>%s</a>" % (self.get_report_url(), "查看报告")

    admin_link.allow_tags = True
    admin_link.short_description = ""

    @property
    def ent_basic(self):
        the_basic = self.c_basic.all().order_by('ENTSTATUS')
        if the_basic.count():
            return the_basic[0]
        return ELBasic()

    @property
    def ent_class(self):
        the_class = self.c_class.all().order_by('-id')
        if the_class.count():
            return the_class[0]
        return ELClass()

    # 从管理人员表获取法人信息
    def _faren(self):
        the_faren = list(ELManager.objects.filter(entobj=self.entid, LEREPSIGN=1).values_list("NAME", flat=True))
        if len(the_faren):
            return the_faren[0]
        return ""

    _faren.short_description = "法定代表人"

    faren = property(_faren)

    # 从管理人员表获取法人电话
    def _farentel(self):
        the_farentel = list(ELManager.objects.filter(entobj=self.entid, LEREPSIGN=1).values_list("TEL", flat=True))
        if len(the_farentel):
            return the_farentel[0]
        return ""

    _farentel.short_description = "法人电话"

    farentel = property(_farentel)

    # 根据企业名称获取企业对象的快捷函数，处理名称中的英文括号问题
    @staticmethod
    def get_company_by_title(the_title):
        if len(the_title) > 3:
            the_coms = ELPost.objects.filter(ENTNAME=the_title)
            if the_coms.count() == 0 and ("(" in the_title or ")" in the_title):
                the_coms = ELPost.objects.filter(ENTNAME=the_title.replace("(", "（").replace(")", "）"))
            if the_coms.count() == 0 and ("（" in the_title or "）" in the_title):
                the_coms = ELPost.objects.filter(ENTNAME=the_title.replace("（", "(").replace("）", ")"))
            if the_coms.count() == 0 and ("(" in the_title or ")" in the_title or "（" in the_title or "）" in the_title):
                the_coms = ELPost.objects.filter(ENTNAME=the_title.replace("(", "").replace(")", "").replace("（", "").replace("）", ""))
            if the_coms.count():
                return the_coms[0]
            else:
                # 继续查找曾用名表
                the_coms = ELNameHistory.objects.filter(ENTNAME=the_title)
                if the_coms.count() == 0 and ("(" in the_title or ")" in the_title):
                    the_coms = ELNameHistory.objects.filter(ENTNAME=the_title.replace("(", "（").replace(")", "）"))
                if the_coms.count():
                    return the_coms[0].entid
        return None

    # 获取法人id或股东高管的id列表
    @staticmethod
    def get_person_ids(the_entid, with_djg=True):
        fr_personid = list(ELManager.objects.filter(entobj=the_entid, LEREPSIGN=1).values_list("personid", flat=True))
        if len(fr_personid):
            fr_personid = fr_personid[0] if fr_personid[0] else None
        if not with_djg:
            return fr_personid
        else:
            # 股东高管id列表
            other_personids = []
            other_m = list(ELManager.objects.filter(entobj=the_entid, LEREPSIGN=0).values_list("personid", flat=True))
            if len(other_m):
                other_personids.extend(other_m)
            other_i = list(ELInv.objects.filter(entobj=the_entid).values_list("personid", flat=True))
            if len(other_i):
                other_personids.extend(other_i)
            if fr_personid:
                other_personids = list(set(other_personids) - {fr_personid} - {0, None})
            else:
                other_personids = list(set(other_personids) - {0, None})
            return fr_personid, other_personids


# 基础工商登记信息表
class ELBasic(ELBaseModel):
    entobj = models.ForeignKey('company.ELPost', verbose_name='所属企业', db_column='entid', to_field='entid', default=0,
                               related_name='c_basic', help_text='一对一字段，请勿更改')
    ORIREGNO = models.CharField('原注册号', max_length=30, null=True, blank=True)
    ENTTYPE_id = CrossForeignCharField('企业(机构)类型', db_column='ENTTYPE', max_length=4, null=True, blank=True)
    INDUSTRYPHY = models.CharField('行业门类', max_length=1, null=True, blank=True)
    INDUSTRYCO = models.CharField('行业代码', max_length=4, null=True, blank=True)
    ABUITEM = models.TextField('许可经营项目', null=True, blank=True)
    CBUITEM = models.TextField('一般经营项目', null=True, blank=True)
    OPFROM = models.DateField('经营(驻在)期限自', null=True, blank=True)
    OPTO = models.DateField('经营(驻在)期限至', null=True, blank=True)
    POSTALCODE = models.CharField('邮政编码', max_length=6, null=True, blank=True)
    TEL = models.CharField('联系电话', max_length=30, null=True, blank=True)
    EMAIL = models.EmailField('电子邮箱', null=True, blank=True)
    ESDATE = models.DateField('成立日期', null=True, blank=True, db_index=True)
    APPRDATE = models.DateField('核准日期', null=True, blank=True)
    REGORG_id = CrossForeignCharField('登记机关', db_column='REGORG', max_length=8, null=True, blank=True)
    ENTSTATUS = models.CharField('企业状态', max_length=1, blank=True, null=True, db_index=True, choices=ex02_dict)
    REGCAP = models.FloatField('注册资本/万', null=True, blank=True, db_index=True)
    OPSCOPE = models.TextField('经营(业务)范围', null=True, blank=True)
    OPSCOANDFORM = models.TextField('经营范围及方式', null=True, blank=True,
                                    help_text='来自合伙企业基本信息、个人独资企业基本信息、合伙分支与个人分支信息、个体基本信息')
    PTBUSSCOPE = models.TextField('兼营范围', null=True, blank=True)
    DOM = models.CharField('住所', max_length=200, null=True, blank=True)
    DOMDISTRICT_id = CrossForeignCharField('住所所在行政区划', db_column='DOMDISTRICT', max_length=6, null=True, blank=True)
    OPLOC = models.CharField('经营场所', max_length=200, null=True, blank=True)
    OPLOCDISTRICT_id = CrossForeignCharField('经营场所所在行政区划', db_column='OPLOCDISTRICT', max_length=6, null=True, blank=True)
    RECCAP = models.FloatField('实收资本', null=True, blank=True)
    EMPNUM = models.IntegerField('从业人数', null=True, blank=True, db_index=True, help_text='来自合伙企业基本信息、个人独资企业基本信息、合伙分支与个人分支信息、个体基本信息')
    PPRIPID = models.CharField('隶属企业主体身份代码', max_length=36, null=True, blank=True)
    PENTNAME = models.CharField('隶属企业机构名称', max_length=100, null=True, blank=True)
    PREGNO = models.CharField('隶属企业注册号', max_length=30, null=True, blank=True)
    HYPOTAXIS = models.CharField('隶属关系', max_length=2, null=True, blank=True, choices=ca46_dict)
    LOCALADM_id = CrossForeignCharField('属地监管工商所', db_column='LOCALADM', max_length=10, null=True, blank=True)
    CREDLEVEL = models.CharField('信用等级', max_length=1, null=True, blank=True, choices=cf01_dict)
    ASSDATE = models.DateField('信用分类日期', null=True, blank=True)
    ENTCAT = models.CharField('企业分类码', max_length=2, null=True, blank=True, choices=ca14_dict,
                              help_text='该字段内容在总局做整合。不是标准代码，根据地方实际情况增加的。')
    ECOTECDEVZONE_id = CrossForeignCharField('住所所在经济开发区', db_column='ECOTECDEVZONE', max_length=10, null=True, blank=True)
    DOMPRORIGHT = models.CharField('住所产权', max_length=2, null=True, blank=True, choices=ca44_dict)
    INSFORM = models.CharField('设立方式', max_length=2, null=True, blank=True, choices=cd10_dict)
    PARNUM = models.IntegerField('合伙人数', null=True, blank=True)
    LIMPARNUM = models.IntegerField('有限合伙人数', null=True, blank=True)
    PARFORM = models.CharField('合伙方式', max_length=2, null=True, blank=True, choices=ca23_dict)
    EXENUM = models.IntegerField('执行人数', null=True, blank=True)
    SCONFORM = models.CharField('出资方式(个独)或组成形式（个体）', max_length=2, null=True, blank=True, choices=ca27_dict,
                                help_text='对个人独资企业基本信息来说，该指标表示出资方式（个独）EX03，1、以个人财产出资，2、以家庭共有财产作为个人出资；对个体基本信息来说，对应组成形式COMPFORM（来自标准代码CA27）')
    FORCAPINDCODE_id = CrossForeignCharField('外资产业代码', max_length=10, null=True, blank=True, db_column='FORCAPINDCODE',
                                             help_text='来自外商投资企业(机构)基本信息、外商投资企业分支机构基本信息、外国企业常驻代表机构、外国(地区)企业在中国从事生产经营活动CA75')
    MIDPREINDCODE_id = CrossForeignCharField('中西部优势产业代码', max_length=10, null=True, blank=True, db_column='MIDPREINDCODE',
                                             help_text='来自外商投资企业(机构)基本信息、外商投资企业分支机构基本信息、外国企业常驻代表机构、外国(地区)企业在中国从事生产经营活动CA76')
    PROTYPE = models.CharField('项目类型', max_length=2, null=True, blank=True, choices=ca71_dict)
    CONGRO = models.FloatField('投资总额（万元）', null=True, blank=True)
    CONGROCUR_id = CrossForeignCharField('投资总额币种', max_length=3, null=True, blank=True, db_column='CONGROCUR')
    CONGROUSD = models.FloatField('投资总额折万美元', null=True, blank=True)
    REGCAPUSD = models.FloatField('注册资本(金)折万美元', null=True, blank=True)
    REGCAPCUR_id = CrossForeignCharField('注册资本(金)币种', max_length=3, null=True, blank=True, db_column='REGCAPCUR')
    REGCAPRMB = models.FloatField('注册资本(金)折万人民币', null=True, blank=True)
    FORREGCAPUSD = models.FloatField('外方注册资本(金)折万美元', null=True, blank=True)
    FORREGCAPCUR_id = CrossForeignCharField('外方注册资本(金)币种', max_length=3, null=True, blank=True, db_column='FORREGCAPCUR')
    FORRECCAPUSD = models.FloatField('外方实收资本折万美元', null=True, blank=True)
    WORCAP = models.FloatField('营运资金', null=True, blank=True, help_text='指流动资产减流动负债后的差额(外商投资企业分支机构基本信息(补充))')
    CHAMECDATE = models.DateField('转型日期', null=True, blank=True)
    OPRACTTYPE = models.CharField('经营活动类型', max_length=2, null=True, blank=True, choices=ca70_dict)
    FORENTNAME = models.CharField('外国(地区)企业名称', max_length=100, null=True, blank=True, help_text='来自外国企业常驻代表机构、外国(地区)企业在中国从事生产经营活动')
    DEPINCHA = models.CharField('主管部门', max_length=100, null=True, blank=True)
    COUNTRY_id = CrossForeignCharField('国别(地区)', max_length=3, null=True, blank=True, db_column='COUNTRY')
    ITEMOFOPORCPRO = models.TextField('承包工程或经营管理项目', null=True, blank=True)
    CONOFCONTRPRO = models.TextField('承包工程或经营管理内容', null=True, blank=True)
    FORDOM = models.CharField('境外住所', max_length=100, null=True, blank=True)
    FORREGECAP = models.FloatField('境外注册资本', null=True, blank=True)
    FOROPSCOPE = models.TextField('境外经营范围', null=True, blank=True)
    FOREIGNBODYTYPE = models.CharField('境外主体类型', max_length=200, null=True, blank=True, help_text='仅适用于主体类型为“代表机构”和“外国企业在华从事生产经营活动”')
    ENTPROPERTY = models.CharField('企业性质', max_length=2, null=True, blank=True, choices=ex15_dict)
    MANACATE = models.CharField('经营类别', max_length=4, null=True, blank=True, choices=ex19_dict)

    class Meta:
        verbose_name = '企业工商信息'
        verbose_name_plural = '企业工商信息'
        db_table = 'company_basic'

    def _entid(self):
        entid = ELPost.objects.filter(entid=self.entobj_id).first()
        if entid:
            return entid
        return ""

    _entid.short_description = "所属企业"

    entid = property(_entid)

    def __unicode__(self, *args, **kwargs):
        return u'%s的工商信息' % self.entid

    def _enttype(self):
        the_enttype = list(ELCA16.objects.filter(code=self.ENTTYPE_id).values_list("name", flat=True))
        if len(the_enttype):
            return the_enttype[0]
        return ""

    _enttype.short_description = "企业(机构)类型"

    ENTTYPE = property(_enttype)

    def _regorg(self):
        the_regorg = list(ELCA11.objects.filter(code=self.REGORG_id).values_list("name", flat=True))
        if len(the_regorg):
            return the_regorg[0]
        return ""

    _regorg.short_description = "登记机关"

    REGORG = property(_regorg)

    def _domdistrict(self):
        return ELRegion.get_region(self.DOMDISTRICT_id)

    _domdistrict.short_description = "住所所在行政区划"

    DOMDISTRICT = property(_domdistrict)

    def _oplocdistrict(self):
        return ELRegion.get_region(self.OPLOCDISTRICT_id)

    _oplocdistrict.short_description = "经营场所所在行政区划"

    OPLOCDISTRICT = property(_oplocdistrict)

    def _localadm(self):
        the_localadm = list(ELCA12.objects.filter(code=self.LOCALADM_id).values_list("name", flat=True))
        if len(the_localadm):
            return the_localadm[0]
        return ""

    _localadm.short_description = "属地监管工商所"

    LOCALADM = property(_localadm)

    def _ecotecdevzone(self):
        the_ecotecdevzone = list(ELCA73.objects.filter(code=self.ECOTECDEVZONE_id).values_list("name", flat=True))
        if len(the_ecotecdevzone):
            return the_ecotecdevzone[0]
        return ""

    _ecotecdevzone.short_description = "住所所在经济开发区"

    ECOTECDEVZONE = property(_ecotecdevzone)

    def _forcapindcode(self):
        the_forcapindcode = list(ELCA75.objects.filter(code=self.FORCAPINDCODE_id).values_list("name", flat=True))
        if len(the_forcapindcode):
            return the_forcapindcode[0]
        return ""

    _forcapindcode.short_description = "外资产业代码"

    FORCAPINDCODE = property(_forcapindcode)

    def _midpreindcode(self):
        the_midpreindcode = list(ELCA76.objects.filter(code=self.MIDPREINDCODE_id).values_list("name", flat=True))
        if len(the_midpreindcode):
            return the_midpreindcode[0]
        return ""

    _midpreindcode.short_description = "中西部优势产业代码"

    MIDPREINDCODE = property(_midpreindcode)

    def _congrocur(self):
        the_congrocur = list(ELCA04.objects.filter(code=self.CONGROCUR_id).values_list("name", flat=True))
        if len(the_congrocur):
            return the_congrocur[0]
        return ""

    _congrocur.short_description = "投资总额币种"

    CONGROCUR = property(_congrocur)

    def _regcapcur(self):
        the_regcapcur = list(ELCA04.objects.filter(code=self.REGCAPCUR_id).values_list("name", flat=True))
        if len(the_regcapcur):
            return the_regcapcur[0]
        return ""

    _regcapcur.short_description = "注册资本(金)币种"

    REGCAPCUR = property(_regcapcur)

    def _forregcapcur(self):
        the_forregcapcur = list(ELCA04.objects.filter(code=self.FORREGCAPCUR_id).values_list("name", flat=True))
        if len(the_forregcapcur):
            return the_forregcapcur[0]
        return ""

    _forregcapcur.short_description = "外方注册资本(金)币种"

    FORREGCAPCUR = property(_forregcapcur)

    def _country(self):
        the_country = list(ELCA02.objects.filter(code=self.COUNTRY_id).values_list("name", flat=True))
        if len(the_country):
            return the_country[0]
        return ""

    _country.short_description = "国别(地区)"

    COUNTRY = property(_country)


# 企业id映射
class ELPripid(ELBaseModel):
    entid = models.IntegerField('所属企业', default=0)
    PRIPID = models.CharField('总局PRIPID', max_length=36, null=True, blank=True, db_index=True)

    class Meta:
        verbose_name = '企业id映射'
        verbose_name_plural = '企业id映射'
        app_label = "companyplus"
        db_table = 'company_id_ent_pripid'

    def __unicode__(self):
        return u'%s的id映射' % self.entid


# 企业分类信息表
class ELClass(ELBaseModel):
    entobj = models.ForeignKey('company.ELPost', verbose_name='所属企业', db_column='entid', default=0,
                               related_name='c_class', to_field='entid')
    region_id_id = CrossForeignCharField('所在地区', db_column="region_id", max_length=6,
                                         db_index=True, null=True, blank=True)
    nic_id_id = CrossForeignCharField('行业分类', db_column="nic_id", max_length=5,
                                      db_index=True, null=True, blank=True)
    el_nic_id_id = CrossForeignCharField('行业分类', db_column="el_nic_id", max_length=5,
                                         db_index=True, null=True, blank=True)
    el_seic_id_id = CrossForeignCharField('战兴产业分类', db_column="el_seic_id", max_length=7,
                                          db_index=True, null=True, blank=True)
    lat = models.DecimalField("纬度", max_digits=10, decimal_places=7, null=True, blank=True, db_index=True)
    lng = models.DecimalField("经度", max_digits=10, decimal_places=7, null=True, blank=True, db_index=True)
    glevel = models.SmallIntegerField('级别', null=True, blank=True, help_text='经纬度接口返回的级别')

    class Meta:
        verbose_name = '企业分类信息'
        verbose_name_plural = '企业分类信息'
        db_table = 'el_company_class'

    def _entid(self):
        entid = ELPost.objects.filter(entid=self.entobj_id).first()
        if entid:
            return entid
        return ""

    _entid.short_description = "所属企业"

    entid = property(_entid)

    def __unicode__(self):
        return u'%s的分类信息' % self.entid

    def admin_link(self):
        url_name = "company_report"
        kwargs = {"entid": self.entid.entid}
        return "<a href='%s' target='_blank'>%s</a>" % (reverse(url_name, kwargs=kwargs), "查看报告")

    admin_link.allow_tags = True
    admin_link.short_description = ""

    def _region_id(self):
        return ELRegion.get_region(self.region_id_id, m="obj")

    _region_id.short_description = "所在地区"

    region_id = property(_region_id)

    def _nic_id(self):
        the_nic = ELNic.objects.filter(code=self.nic_id_id).first()
        if the_nic:
            return the_nic
        return ""

    _nic_id.short_description = "行业分类"

    nic_id = property(_nic_id)

    def _el_nic_id(self):
        the_nic = ELNic.objects.filter(code=self.el_nic_id_id).first()
        if the_nic:
            return the_nic
        return ""

    _el_nic_id.short_description = "行业分类"

    el_nic_id = property(_el_nic_id)

    def _el_seic_id(self):
        the_seic = ELSeic.objects.filter(code=self.el_seic_id_id).first()
        if the_seic:
            return the_seic
        return ""

    _el_seic_id.short_description = "战兴产业分类"

    el_seic_id = property(_el_seic_id)

    def _geocode(self):
        if self.lat and self.lng:
            return '%s,%s' % (self.lat, self.lng)
        return ''

    _geocode.short_description = "经纬度"

    geocode = property(_geocode)


# 企业简称表
class ELShort(EntIdable):
    ENTNAME = models.CharField('企业全称', max_length=150, db_index=True, null=True)
    shortname = models.CharField('简称', max_length=100, db_index=True, null=True)
    NAMEIND = models.CharField('名称行业', max_length=36, null=True, blank=True)
    updated = models.DateTimeField('更新时间', null=True, blank=True, auto_now=True)

    class Meta:
        verbose_name = '企业简称表'
        verbose_name_plural = '企业简称表'
        app_label = "companyplus"
        db_table = 'el_company_short'

    def __unicode__(self):
        return u'%s的简称' % self.entid


# 企业曾用名表
class ELNameHistory(EntIdable):
    ENTNAME = models.CharField('曾用名', max_length=150, db_index=True, null=True)

    class Meta:
        verbose_name = '企业曾用名'
        verbose_name_plural = '企业曾用名'
        app_label = "companyplus"
        db_table = 'el_company_name_history'

    def __unicode__(self):
        return u'%s的曾用名' % self.entid


# 企业标签表
class ELTags(ELBaseModel):
    name = models.CharField("标签名称", max_length=50, null=True)
    count = models.IntegerField('已分配的企业数', null=True, blank=True)

    class Meta:
        verbose_name = '企业标签'
        verbose_name_plural = '企业标签'
        app_label = "companyplus"
        db_table = 'el_company_tags'

    def __unicode__(self):
        return u'%s' % self.name


# 已分配的企业标签
class ELTagsAssigned(EntIdable):
    tag_id = models.ForeignKey('companyplus.ELTags', verbose_name='标签id', db_column='tag_id')
    created = models.DateField('标签生效日期', null=True, blank=True)
    updated = models.DateTimeField('更新时间', null=True, blank=True, auto_now=True)

    class Meta:
        verbose_name = '已分配的企业标签'
        verbose_name_plural = '已分配的企业标签'
        app_label = "companyplus"
        db_table = 'el_company_tags_assigned'

    def __unicode__(self):
        return u'%s-%s' % (self.tag_id.name, self.entid)


# 个人信息表
class ELPerson(ELBaseModel):
    personid = models.IntegerField('个人ID', primary_key=True)
    NAME = models.CharField('姓名', max_length=200, null=True, blank=True)
    CERNO = models.CharField('证件号码', max_length=32, db_index=True)
    CERTYPE = models.CharField('证件类型', max_length=1, null=True, blank=True, choices=cb16_dict)
    SEX = models.CharField('性别', max_length=2, null=True, blank=True, choices=cb17_dict)
    NATDATE = models.DateField('出生日期', null=True, blank=True)
    DOM = models.CharField('住址', max_length=100, null=True, blank=True)
    POSTALCODE = models.CharField('邮编', max_length=6, null=True, blank=True)
    TEL = models.CharField('电话', max_length=30, null=True, blank=True)
    LITDEG = models.CharField('文化程度', max_length=3, null=True, blank=True, choices=cb31_dict)
    NATION = models.CharField('民族', max_length=3, null=True, blank=True, choices=cb32_dict)
    POLSTAND = models.CharField('政治面貌', max_length=3, null=True, blank=True, choices=cb30_dict)
    OCCST = models.CharField('职业状况', max_length=128, null=True, blank=True, help_text='同时对应个人独资企业投资人信息的，申请前职业状况OccStBeApp')
    OFFSIGN = models.CharField('公务员标志', max_length=2, null=True, blank=True, choices=ex06_dict)
    COUNTRY_id = CrossForeignCharField('国别(地区)', max_length=3, null=True, blank=True, db_column='COUNTRY')
    NOTORG = models.CharField('身份核证文件核(公)证机构(人)', max_length=100, null=True, blank=True)
    NOTDOCNO = models.CharField('身份核证文件编号', max_length=50, null=True, blank=True)
    updated = models.DateTimeField('更新时间', null=True, blank=True, auto_now=True)

    class Meta:
        verbose_name = '个人信息表'
        verbose_name_plural = '个人信息表'
        db_table = 'el_person'

    def __unicode__(self):
        return u'%s' % self.NAME

    @property
    def birthday(self):
        try:
            if self.NATDATE:
                return self.NATDATE.strftime("%Y-%m-%d")
            elif self.CERNO and len(str(self.CERNO)) == 18:
                return self.CERNO[6:10] + "-" + self.CERNO[10:12] + "-" + self.CERNO[12:14]
            elif self.CERNO and len(str(self.CERNO)) == 15:
                return "19" + self.CERNO[6:8] + "-" + self.CERNO[8:10] + "-" + self.CERNO[10:12]
            return ""
        except Exception:
            return ""


# 信用评分主表
class ELCredit(EntIdable):
    year = models.SmallIntegerField('评价日期', null=True, db_index=True)
    index_total = models.SmallIntegerField('总评分', null=True, db_index=True)
    index_2_1 = models.FloatField('高管资历', blank=True, null=True)
    index_2_2 = models.FloatField('经营能力', blank=True, null=True)
    index_2_3 = models.FloatField('经营稳定性', blank=True, null=True)
    index_2_4 = models.FloatField('发展能力', blank=True, null=True)
    index_2_5 = models.FloatField('资本实力', blank=True, null=True)
    index_3_1 = models.FloatField('管理团队教育背景', blank=True, null=True)
    index_3_2 = models.FloatField('高管行业任职经验', blank=True, null=True)
    index_3_3 = models.FloatField('管理团队管理能力', blank=True, null=True)
    index_3_4 = models.FloatField('盈利能力', blank=True, null=True)
    index_3_5 = models.FloatField('经营成本', blank=True, null=True)
    index_3_6 = models.FloatField('资金压力', blank=True, null=True)
    index_3_7 = models.FloatField('资产周转', blank=True, null=True)
    index_3_8 = models.FloatField('市场地位', blank=True, null=True)
    index_3_9 = models.FloatField('经营波动', blank=True, null=True)
    index_3_10 = models.FloatField('权力稳定', blank=True, null=True)
    index_3_11 = models.FloatField('财务增长', blank=True, null=True)
    index_3_12 = models.FloatField('股东特质', blank=True, null=True)

    class Meta:
        verbose_name = '信用评分主表'
        verbose_name_plural = '信用评分主表'
        db_table = 'el_credit'

    def __unicode__(self):
        return u'%s' % self.id


# 引入子model的虚变量，以防import被优化
models_imported = [models_relation_imported, models_charge_imported, models_law_imported, models_stock_imported, models_geti_imported,
                   models_registe_imported]

# 连接信号接收函数
post_save.connect(save_signal_func, sender=ELPost, dispatch_uid="f68c39e92ffe")

# 搜索引擎地址，精确到 /index/doc-type/
elasticsearch_index = {
    # "company": "element/company1609/",  # 企业
    "company": "element-index-170707/company170707/",  # 企业


    "geti": "geti1609/element/",  # 个体户
                       "cancel": "cancel1609/element/",  # 企业注吊销
                       "geticancel": "geticancel1609/element/",  # 个体户注吊销
                       "tax": "tax2014/element/",  # 税务年度
                       "hg": "hg1607/element/",  # 海关月度
                       "geocode": "geocode/element/"  # 经纬度（含企业和个体）
                       }
